import { Button, Tree, message } from 'antd'
import React, { useEffect, useState } from 'react'

import { Root } from '@/types'
import { Root2 } from '@/types/menuItem'
import type { TreeProps } from 'antd'
import { useAppSelector } from '@/store/hooks'
import { useNavigate } from 'react-router-dom'
import { useUpdatePermissions } from '@/api/query'

// 递归转换数据，去掉zh和en
const transformLabelToZh = (menu: Root2): Root => {
  const newMenu = {
    ...menu,
    label: menu.label.zh,
    children: menu.children ? menu.children.map(transformLabelToZh) : undefined
  }
  return newMenu
}
// 递归将选择的字符串数组从菜单权限中找出来
const findChecked = (menu: Root, checkedKeys: string[]): Root => {
  return menu.reduce((acc: Root, item) => {
    if (checkedKeys.includes(item.key)) {
      acc.push({
        ...item,
        children: item.children
          ? findChecked(item.children, checkedKeys)
          : undefined
      })
    } else if (item.children) {
      const children = findChecked(item.children, checkedKeys)
      if (children.length > 0) {
        acc.push({
          ...item,
          children: children
        })
      }
    }
    return acc
  }, [])
}

const App: React.FC = () => {
  const Navigate = useNavigate()
  const { Menus } = useAppSelector((state) => state.front)
  const { menuList, id } = useAppSelector((state) => state.user)
  const [newMenus, setNewMenus] = useState<Root[]>([])
  const [checkedKeys, setCheckedKeys] = useState<string[]>([])
  useEffect(() => {
    if (Menus) {
      const newMenus = Menus.map(transformLabelToZh)
      setNewMenus(newMenus)
      return
    }
  }, [Menus])
  useEffect(() => {
    if (menuList) {
      const newSelected = menuList.map((item: Root2) => item.key)
      setCheckedKeys(newSelected)
    }
  }, [menuList])
  const onCheck: TreeProps['onCheck'] = (checkedKeys: string[]) => {
    setCheckedKeys(checkedKeys)
  }
  const [newRole, setNewRole] = useState<Root>([])
  const { mutate } = useUpdatePermissions(newRole)
  const Keep = () => {
    const newRole = findChecked(Menus, checkedKeys)
    setNewRole(newRole)
    mutate(id)
    message.success('保存成功')
    Navigate(-1)
  }
  if (newMenus.length === 0) {
    return <div>loading</div>
  }
  return (
    <>
      <Tree
        checkable
        defaultExpandAll={true}
        checkedKeys={checkedKeys}
        onCheck={onCheck}
        treeData={newMenus}
        fieldNames={{
          title: 'label',
          key: 'key'
        }}
      />
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
          marginTop: '1%'
        }}
      >
        <Button type="primary" onClick={Keep}>
          保存
        </Button>
        <Button
          onClick={() => {
            setCheckedKeys([])
          }}
        >
          清空
        </Button>
      </div>
    </>
  )
}

export default App
